import cv2
import csv
import os
import time

# 鼠标回调函数
def click_event(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        param['clicked'] = True
        param['x'] = x
        param['y'] = y

def main(video_file, start_time, end_time, output_file):

    # 用户输入

    # 打开视频
    cap = cv2.VideoCapture(video_file)
    if not cap.isOpened():
        print("无法打开视频文件")
        return

    fps = cap.get(cv2.CAP_PROP_FPS)
    start_frame = int(start_time * fps)
    end_frame = int(end_time * fps)

    cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)

    data = []
    frame_count = start_frame

    cv2.namedWindow('frame')

    while cap.isOpened() and frame_count <= end_frame:
        ret, frame = cap.read()
        if not ret:
            break

        click_data = {'clicked': False, 'x': 0, 'y': 0}
        cv2.setMouseCallback('frame', click_event, click_data)

        cv2.imshow('frame', frame)
        key = cv2.waitKey(0)  # 等待用户输入

        if click_data['clicked']:
            current_time = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000
            data.append([current_time, click_data['x'], click_data['y']])
            print(f"记录: 时间 {current_time:.2f}s, 位置 ({click_data['x']}, {click_data['y']})")
        else:
            print("未点击，跳过这一帧")

        if key == 27:  # ESC键退出
            break

        frame_count += 1

    cap.release()
    cv2.destroyAllWindows()

    # 保存数据
    with open(output_file, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['time', 'x', 'y'])
        writer.writerows(data)

    print(f"数据已保存到 {output_file}")

if __name__ == "__main__":
    video_file = "../Videos/自由落体实验.mp4"
    time_list = [
        (2.784, 3.132),
        (6.916, 7.282),
        (10.541, 10.917),
        (14.683, 15.032),
        (18.623, 19.032)
    ]
    for j, time_pair in enumerate(time_list):
        start_time = time_pair[0]
        end_time = time_pair[1]
        output_file = f'data/free_fall_data_{j}.csv'
        main(video_file, start_time, end_time, output_file)
